// $(function(){
//     flow.init();
// });
//
// var flow = new XhFlow();
function XhFlow(_dom, _moduleName, _tableName){
    'use strict';
    return {
        config: {
            namePrefix: '_xh_flow_',
            classPrefix: 'xh-flow-'
        },
        dom: {
            main: _dom,
            save: null,
            commit: null,
            reject: null,
            finish: null,
            revoke: null
        },
        baseParams: {
            moduleName: _moduleName,
            tableName: _tableName
        },
        params: {
            users: [],
            depUser: {},        //部门用户缓存 depId: users
            tagFlow: {}         //流程列表缓存 tag: flowList
        },
        clear: function () {
            this.dom.main.html('');
            return this;
        },
        create: function (tag) {
            var $this = this;

            //初始化，有缓存则取缓存
            if (typeof $this.params.tagFlow[tag] === 'object') {
                $this.funObj().initDepUser(function () {
                    $this.funObj().afterCreate($this.params.tagFlow[tag]);
                });
                return true;
            }
            $this.tool.ajaxRequest('Flow/getFlowTemplate', {tag: tag}, {check: true}, function (flowList) {
                $this.params.tagFlow[tag] = flowList;
                $this.create(tag);
            });
        },
        commit: function (mainId) {
            this.funObj().commit(mainId);
        },
        getPower: function (mainId, callback) {
            this.funObj().getPower(mainId, callback);
        },
        setDom: function (domObj) {
            this.dom = $.extend({}, this.dom, domObj);
        },
        setBtnStatus: function (power) {
            var $this = this;
            $.each(power, function (key, value) {
                if ($this.dom[key] && $this.dom[key].length) {
                    if (value) {
                        $this.dom[key].show();
                    }
                    else {
                        $this.dom[key].hide();
                    }
                }
            });
        },
        parse: function (mainId) {
            this.tool.ajaxRequest('Flow/getFlow', this.funObj().extend({mainId: mainId}), {check: true}, function (flow) {

            });
        },
        funObj: function (){
            var $this = this;
            return {
                //初始化人员数据并缓存
                initDepUser: function(_callback) {
                    if ($.isEmptyObject($this.params.users)) {
                        $this.tool.ajaxRequest('Flow/getDepUser', {}, {check: true}, function (data) {
                             $this.params.users = data;
                             _callback.call(this);
                        });
                    }
                    else {
                        _callback.call(this);
                    }
                },
                //根据部门id获取人员列表
                getStaffByDep: function (_depId) {
                    if (!$this.params.depUser[_depId]) {
                        $.each($this.params.users, function (index, row) {
                            if (row.id === _depId) {
                                $this.params.depUser[_depId] = [row];
                                return false;
                            }
                        });
                    }
                    return $this.params.depUser[_depId];
                },
                //新建时创建下拉框，渲染流程
                afterCreate: function (_flowList) {
                    //清空html，创建下拉框
                    $this.dom.main.html('');
                    var selectDom = $('<select class="form-control" name="' + $this.config.namePrefix + 'proId"></select>');
                    $.each(_flowList, function (index, row) {
                        selectDom.append('<option value="' + row.proId + '">' + row.proName + '</option>');
                    });
                    if (_flowList.length === 1) {
                        selectDom.css('display', 'none');
                    }
                    $this.dom.main.append(selectDom);
                    $this.dom.main.append('<input name="' + $this.config.namePrefix + 'proName" style="display: none;"/>');
                    //绑定下拉框选择事件
                    $this.dom.main.find('select[name=' + $this.config.namePrefix + 'proId]').change(function () {
                        var proId = $(this).val();
                        $.each(_flowList, function (index, process) {
                            if (process.proId !== proId) {
                                return true;
                            }
                            $this.funObj().parseFlow(process);
                        });
                        $this.dom.main.find('input[name=' + $this.config.namePrefix + 'proName]').val($(this).find('option:selected').text());
                    }).trigger('change');
                },
                //渲染流程，绑定事件
                parseFlow: function (_process) {
                    var flowDom = $this.dom.main.find('.' + $this.config.classPrefix + 'process');
                    if (flowDom.length) {
                        flowDom.html('');
                    }
                    else {
                        flowDom = $('<div></div>');
                        flowDom.addClass($this.config.classPrefix + 'process');
                        $this.dom.main.append(flowDom);
                    }
                    $.each(_process.nodes, function (index, nodeInfo) {
                        var node = $('<div><div><font></font><a></a><input data-target="user" /><input data-target="info" /><input data-target="name" /></div></div>');
                        node.addClass($this.config.classPrefix + 'node');
                        node.addClass($this.config.classPrefix + 'node-waiting');
                        node.find('font').text(nodeInfo.nodeName || '');
                        node.find('a').addClass('btn btn-sm');
                        node.find('input[data-target=name]').attr('name', $this.config.namePrefix + 'node[' + nodeInfo.code + '][name]').val(nodeInfo.nodeName);
                        node.find('input[data-target=user]').attr('name', $this.config.namePrefix + 'node[' + nodeInfo.code + '][user]');
                        node.find('input[data-target=area]').attr('name', $this.config.namePrefix + 'node[' + nodeInfo.code + '][area]').val(nodeInfo.targetArea);
                        node.find('input[data-target=info]').attr('name', $this.config.namePrefix + 'node[' + nodeInfo.code + '][info]').val(nodeInfo.info);
                        if (nodeInfo.targetUser) {
                            node.find('a').text(nodeInfo.targetUser.split(',').length - 2).addClass('btn-success');
                            node.find('input[data-target=user]').val(nodeInfo.targetUser);
                        }
                        else {
                            node.find('a').text(0).addClass('btn-danger');
                            if (nodeInfo.targetArea && nodeInfo.targetArea.indexOf('dep') === 0) {
                                node.find('a').attr('data-target', 'dep').attr('data-target-id', nodeInfo.targetArea.split(':')[1]);
                            }
                        }
                        flowDom.append(node);
                    });
                    $this.funObj().bindProcessChoice();
                },
                //绑定人员选择事件
                bindProcessChoice: function () {
                    $this.dom.main.find('.xh-flow-node > div > a.btn-danger').click(function () {
                        var _this    = $(this),
                            target   = _this.attr('data-target'),
                            targetId = _this.attr('data-target-id'),
                            data     = $this.params.users;
                        if (target === 'dep') {
                            data = $this.funObj().getStaffByDep(targetId);
                        }
                        swal({
                            title: _this.prev('font').text(),
                            html: '<select id="xh_flow_sl_user"></select>',
                            confirmButtonText: '确认',
                            cancelButtonText: '取消',
                            showCancelButton: true,
                            onOpen: function () {
                                $('#xh_flow_sl_user').select2({
                                    data: data,
                                    multiple: true,
                                    width: '100%',
                                    placeholder: '选择处理人',
                                    allowClear: true
                                });
                            },
                            preConfirm: function (){
                                return new Promise(function (resolve, reject) {
                                    var userIds = $('#xh_flow_sl_user').val();
                                    if (userIds.length < 1) {
                                        reject('未选择用户！');
                                    }
                                    _this.text(userIds.length).next('input[data-target=user]').val(userIds.join(','));
                                    resolve();
                                })
                            }
                        }).then(function (isConfirm){}, function (dismiss){});
                    });
                },
                //提交流程
                commit: function (mainId) {
                    $this.tool.ajaxRequest('Flow/getFlowForCommit', $this.funObj().extend({mainId: mainId}), {check: true}, function (data) {
                        var commitDom = $('<div class="row" style="margin-right: 0;margin-left: 0;">' +
                            '   <div class="col-md-5">' +
                            '       <select id="xh_flow_commit_nextCode" class="form-control"></select>' +
                            '   </div>' +
                            '   <div class="col-md-7">' +
                            '       <input id="xh_flow_commit_userId" style="display: none;"/>' +
                            '       <input id="xh_flow_commit_userName" class="form-control" readonly/>' +
                            '   </div>' +
                            '   <div class="col-md-12" style="margin-top: 10px;">' +
                            '       <input id="xh_flow_commit_code" style="display: none;"/>' +
                            '       <textarea id="xh_flow_commit_advice" class="form-control" rows="5" placeholder="输入意见..."></textarea>' +
                            '   </div>' +
                            '</div>');
                        commitDom.find('#xh_flow_commit_code').val(data.now.code);
                        $.each(data.select, function(code, info) {
                            commitDom.find('#xh_flow_commit_nextCode').append('<option value="'+ info.code +'">'+ info.name +'</option>');
                        });
                        swal({
                            title: data.now.name,
                            html: commitDom[0],
                            confirmButtonText: '提交',
                            cancelButtonText: '取消',
                            showCancelButton: true,
                            showLoaderOnConfirm: true,
                            onOpen: function() {
                                $('#xh_flow_commit_nextCode').change(function() {
                                    $('#xh_flow_commit_userId').val(data.select[$(this).val()].userIds);
                                    $('#xh_flow_commit_userName').val(data.select[$(this).val()].userNames);
                                }).trigger('change');
                            },
                            preConfirm: function (){
                                return new Promise(function (resolve, reject) {
                                    var nextCode = $('#xh_flow_commit_nextCode').val(),
                                        userIds  = $('#xh_flow_commit_userId').val(),
                                        code     = $('#xh_flow_commit_code').val(),
                                        advice   = $('#xh_flow_commit_advice').val();
                                    if (!advice) {
                                        reject('意见不能为空！');
                                        return false;
                                    }
                                    //提交到后台
                                    $this.tool.ajaxRequest('Flow/commit',
                                        $this.funObj().extend({
                                            mainId: mainId,
                                            code: code,
                                            advice: advice,
                                            nextCode: nextCode,
                                            userIds: userIds
                                        }),
                                        {check: true, success: true},
                                        function (){
                                            resolve();
                                        }
                                    );
                                })
                            }
                        }).then(function (isConfirm){}, function (dismiss){});
                    });
                },
                //获取权限
                getPower: function (mainId, _callback) {
                    $this.tool.ajaxRequest('Flow/getPower', $this.funObj().extend({mainId: mainId}), {check: true}, function (result) {
                        _callback.call(this, result);
                    });
                },
                //组合基础参数
                extend: function (_params) {
                    return $.extend({}, $this.baseParams, _params);
                }
            }
        },
        tool: {
            ajaxRequest: function (_url, _params, _options, _callback) {
                var $this = this;
                $.ajax({
                    url: baseUrl + _url,
                    type: 'POST',
                    // data: (typeof _params === 'string' || _params instanceof Array) ? {ids: _params} : (_params || {}),
                    data: _params,
                    dataType: 'json',
                    complete: function(XMLHttpRequest){
                        var result = XMLHttpRequest.responseJSON || XMLHttpRequest.responseText;
                        if(_options.check !== false) {
                            if(result === '' || typeof result === 'string'){
                                $this.showError('请求失败', result);
                                return true;
                            }
                            if(result.error){
                                $this.showError(result.error, typeof result.msg === 'string' ? result.msg : null);
                                return true;
                            }
                        }
                        if(_options.success && result.msg) $this.showSuccess(result.msg);
                        if(_callback) _callback.call(this, result);
                    }
                });
            },
            showError: function (error, msg) {
                swal(error, msg, 'error');
            },
            showSuccess: function (msg) {
                swal(msg, null, 'success');
            }
        }
    }
}